package com.nna88.voz.parserhtml;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.util.Log;

import com.nna88.voz.main.Page;
import com.nna88.voz.util.UserInfo;

public class parser {
	String m_url;
	Document doc;
	UserInfo mUser;
	int mTimeout = 60000;
	public parser(String url){
		m_url = url;
		mUser = new UserInfo();
	}
	public String getUrl(){
		return m_url;
	}
	public void setUrl(String url){
		m_url = url;
	}
	public Document login(UserInfo mUser){
		this.mUser = mUser;
    	try {
			Response res = Jsoup.connect("http://vozforums.com/login.php?do=login")
					  .timeout(60000)
					  .data("do","login")
					  .data("vb_login_username",mUser.User())
					  .data("cookieuser", "1")
					  .data("vb_login_password",mUser.Pass())
					  .data("s", " ")
					  .data("securitytoken", mUser.Token())
					  .data("vb_login_md5password", mUser.md5Pass())
					  .data("vb_login_md5password_utf", mUser.md5Pass())
					  .method(Method.POST)
				      .execute();

			if(res.cookie("vfuserid") != null){
				mUser.cookies(res.cookies());
				mUser.setLogin(true); 
				return getDoc();
			}else 
				return null;	
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	public Document Logout(){
    	String urlLogout=null;
    	urlLogout = "http://vozforums.com/login.php?do=logout&"+
    			"logouthash=" + mUser.Token();
    	try {
    		Response  res = Jsoup.connect(urlLogout)
						.timeout(60000)
						.method(Method.POST)
						.execute();
			mUser.cookies(res.cookies());
			mUser.setLogin(false); 
			return getDoc();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
    }
	/**
	 * Get text quote
	 * @param type : 0: reply, 1: edit
	 * @param id: id post
	 * @return
	 */
	public Document quoteGet(int type, int id){
    	try {
    		String temp = null;
    		if(type == Page.REQUEST_QUOTE)//new reply
    			temp = "http://vozforums.com/newreply.php?do=newreply&p=";
    		else if ((type == Page.REQUEST_EDIT) || (type == Page.REQUEST_DELETE) )//edit post
    			temp = "http://vozforums.com/editpost.php?do=editpost&p=";
    		else if (type == Page.REQUEST_REPLY) // quickreply
    			return null;
    		m_url = temp + String.valueOf(id);
			Response res = Jsoup.connect(m_url)
					  .timeout(60000)  
					  .cookies(mUser.cookies())
					  .method(Method.GET)
				      .execute();
			Log.d("nna","quoteget ok");
			Document doc2 = res.parse();
			return doc2;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
    public Document getDoc(){
		try {
			if(mUser.cookies() == null){
				Connection con1 = Jsoup.connect(m_url);
				doc = con1.get();
			}else{
				doc = Jsoup.connect(m_url)
						.timeout(60000)
						.cookies(mUser.cookies())
						.get();
			}
	
			if(doc.select("td[class*=tcat]").first().text().equals("vBulletin Message")){
				return null;
			}else{
				m_url = doc.baseUri();
				return doc;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
    public Document UnSubscribe(String id ){
    	try {
    		
    		Response res = Jsoup.connect("http://vozforums.com/subscription.php?do=removesubscription&t="+id)
					  .timeout(60000)
					  .cookies(mUser.cookies())
					  .method(Method.GET)
				      .execute();
			return getDoc();
			//return parser();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

    }
    public Document Subscribe(String id,String secToken){
    	try {
    		
			Response res = Jsoup.connect("http://vozforums.com/subscription.php?do=doaddsubscription&threadid="+id)
					  .timeout(60000)
					  .cookies(mUser.cookies())
					  .data("do","doaddsubscription")
	    			  .data("threadid",id)
	    			  .data("s"," ")
	    			  .data("url","index.php")
	    			  .data("emailupdate","0")
	    			  .data("folderid","0")
	    			  .data("securitytoken",secToken)
					  .method(Method.POST)
				      .execute();
			return getDoc();
			//return parser();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

    }
    public int PostQuoteReply(String message){
//    	Element eleUrl = mainElement.select("form[action*=newreply.php?do=postreply]").first();
//    	Element eleSecurity = mainElement.select("input[name*=securitytoken]").first();
//    	Element elePostHash = mainElement.select("input[name*=posthash]").first();
//    	Element elePostStartTime =mainElement.select("input[name*=poststarttime]").first();
//    	Element eleP =mainElement.select("input[name=p]").first();
//    	Element eleTitle =mainElement.select("input[name=title]").first();
//    	String url,secToken = null,postHash=null,postStartTime=null,p=null,title=null;
//    	if(eleSecurity != null )secToken = eleSecurity.attr("value");
//    	if(elePostHash != null) postHash = elePostHash.attr("value");
//    	if(elePostStartTime != null) postStartTime = elePostStartTime.attr("value");
//    	if(eleP != null) p = eleP.attr("value");
//    	if(eleTitle != null) title = eleTitle.attr("value");
//    	try {
//	    	if(eleUrl != null){
//	    		url = eleUrl.attr("action");
//	    		url = url.replace("&amp;","&");
//	    		res = Jsoup.connect("http://vozforums.com/" + url)
//	    				  .timeout(60000)
//	    				  .cookies(mUser.cookies())
//	    				  .data("title",title)
//	    				  .data("message",message)
//						  .data("wysiwyg","0")
//						  .data("securitytoken",secToken)
//						  .data("do", "postreply")
//						  .data("t", url.split("=")[2])
//						  .data("p", p)
//						  .data("specifiedpost", "1")
//						  .data("s", " ")
//						  .data("posthash", postHash)
//						  .data("poststarttime", postStartTime)
//						  .data("loggedinuser",mUser.UserId())
//						  .data("multiquoteempty", "")
//						  .data("sbutton", "Post Quick Reply")
//						  .data("parseurl", "1")
//						  .data("emailupdate", "9999")
//						  .data("rating", "0")
//						  .method(Method.POST)
//					      .execute();
//	    		doc = res.parse();
//	    		ListContains.clear();
//	    		PaserExecute();
//	    		return 0;
//	    	}
//
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return -1;
//		}
    	return -1;
    }
    /**
     * 
     * @param message
     * @param url
     * @param title
     * @param secToken
     * @param p
     * @param postHash
     * @param postStartTime
     * @return
     */
    public Document PostEditReply(int type, String message,String url,String title, String secToken,
    		String p,String postHash, String postStartTime ){
    	try {
    		Response res;
    		if(type == 0){
    		 res = Jsoup.connect("http://vozforums.com/" + url)
    				  .timeout(60000)
    				  .cookies(mUser.cookies())
    				  .data("title",title)
    				  .data("message",message)
					  .data("wysiwyg","0")
					  .data("s", " ")
					  .data("securitytoken",secToken)
					  .data("do", "updatepost")
					  .data("p", p)
					  .data("posthash", postHash)
					  .data("poststarttime", postStartTime)
					  .data("sbutton", "Save Changes")
					  .data("parseurl", "1")
					  .data("emailupdate", "9999")
					  .method(Method.POST)
				      .execute();
    		}else{
    			 res = Jsoup.connect("http://vozforums.com/" + url)
      				  .timeout(60000)
      				  .cookies(mUser.cookies())
      				  .data("s","")
      				  .data("securitytoken",secToken)
      				  .data("p", p)
      				  .data("url","http://vozforums.com/showthread.php?p="+p+"&highlight=")
      				  .data("do", "deletepost")
      				  .data("deletepost", "delete")
      				  .data("reason", "")		  
  					  .method(Method.POST)
  				      .execute();
    		}
    		m_url = res.url().toString();
    		return res.parse();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
    public Document PostQuickReply(String message,String url, String secToken){
    	try {
    		Response res = Jsoup.connect("http://vozforums.com/" + url)
    				  .timeout(60000)
    				  .cookies(mUser.cookies())
    				  .data("message",message)
					  .data("wysiwyg","0")
					  .data("styleid", "0")
					  .data("fromquickreply", "1")
					  .data("s", " ")
					  .data("securitytoken",secToken)
					  .data("do", "postreply")
					  .data("t", url.split("=")[2])
					  .data("p", "who cares")
					  .data("specifiedpost", "0")
					  .data("parseurl", "1")
					  .data("loggedinuser",mUser.UserId())
					  .data("sbutton", "Post Quick Reply")
					  .method(Method.POST)
				      .execute();
    		m_url = res.url().toString();
    		return res.parse();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
    }
}
